import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, logout as logoutApi, getCurrentUser } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  // 安全地解析 localStorage 中的 userInfo
  const getUserInfoFromStorage = () => {
    try {
      const userInfoStr = localStorage.getItem('userInfo')
      if (!userInfoStr) return {}
      const parsed = JSON.parse(userInfoStr)
      return parsed || {}
    } catch (error) {
      console.error('Failed to parse userInfo:', error)
      return {}
    }
  }

  // 直接从 localStorage 初始化，确保刷新后状态正确
  const storedToken = localStorage.getItem('token') || ''
  const token = ref(storedToken)
  const userInfo = ref(getUserInfoFromStorage())
  const isLoggedIn = ref(!!storedToken)
  
  // 打印初始化状态，方便调试
  console.log('Auth store initialized:', {
    hasToken: !!storedToken,
    isLoggedIn: isLoggedIn.value,
    userInfo: userInfo.value
  })
  
  // 监听token变化，同步更新isLoggedIn状态
  const updateLoginStatus = () => {
    isLoggedIn.value = !!token.value
  }

  // 初始化：从 localStorage 恢复状态（用于手动刷新）
  const initializeAuth = () => {
    const storedToken = localStorage.getItem('token')
    if (storedToken) {
      token.value = storedToken
      userInfo.value = getUserInfoFromStorage()
      updateLoginStatus()
      console.log('Auth state manually initialized:', {
        hasToken: !!token.value,
        isLoggedIn: isLoggedIn.value
      })
    }
  }

  const login = async (username, password) => {
    try {
      const response = await loginApi(username, password)
      token.value = response.token
      userInfo.value = response.userInfo
      
      localStorage.setItem('token', response.token)
      localStorage.setItem('userInfo', JSON.stringify(response.userInfo))
      
      // 确保登录状态正确更新
      updateLoginStatus()
      
      return { success: true }
    } catch (error) {
      console.error('Login error:', error)
      const message = error.response?.data?.detail || error.message || '登录失败'
      return { success: false, message }
    }
  }

  const logout = async () => {
    try {
      if (token.value) {
        await logoutApi()
      }
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      // 无论API调用是否成功，都清除本地状态
      token.value = ''
      userInfo.value = {}
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 确保登录状态正确更新
      updateLoginStatus()
    }
  }

  const refreshUserInfo = async () => {
    try {
      if (token.value) {
        const response = await getCurrentUser()
        userInfo.value = response
        localStorage.setItem('userInfo', JSON.stringify(response))
        return { success: true }
      }
    } catch (error) {
      console.error('Refresh user info error:', error)
      // 如果获取用户信息失败，可能token已过期，执行登出
      await logout()
      return { success: false, message: '获取用户信息失败' }
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    logout,
    refreshUserInfo,
    updateLoginStatus,
    initializeAuth
  }
})
